<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/18
 * Time: 15:08
 */
include_once "/Model.class.php";
class XxxPhp {
    protected $_config = array();

    public function __construct($config)
    {
        $this->_config = $config;
        Model::$_config = $config;
    }

    public function run() {
//     获取请求的url(不包括域名)
        $url = $_SERVER['REQUEST_URI'];

//        获取action、method名称
        $urlArr = explode('/', $url);
        array_splice($urlArr, 0, 3);

        $count = count($urlArr);

        $controllerName = '';
        $action = '';

        $defaultController = $this->_config['default_controller'];
        $defaultAction = $this->_config['default_action'];

        if($count == 0) {
            $controllerName = $defaultController;
            $action = $defaultAction;
        } else if ($count == 1) {
            $controllerName = $urlArr[0];
            $action = $defaultAction;
            array_shift($urlArr);
        } else {
            $controllerName = $urlArr[0];
            array_shift($urlArr);
            $action = $urlArr[0];
            array_shift($urlArr);
        }


        $controller = $controllerName . 'Controller';

//        设置model向对应的表
        Model::$_table = $controllerName;

//        根据传递的controller加载相应的文件
        $controller = ucfirst($controller);
        $controllerUrl = APP_PATH . 'application/' . 'controllers/' . $controller . '.php';

        include $controllerUrl;

//    实例化controller
        $dispatch = new $controller($controllerName, $action);

//        获取param

        $param = $this->arr2arr($urlArr);

//        根据action调用controller的action方法
        $dispatch->$action($param);
    }

    public function arr2arr($urlArr) {
        $param = array();
        for ($i = 0; $i < count($urlArr); $i++) {
            if ($i % 2 == 1) {
                $lastI = $i -1;
                $param[$urlArr[$lastI]] = $urlArr[$i];
            }
        }
        return $param;
    }
}
